package common;

import java.io.File;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import com.oreilly.servlet.MultipartRequest;

public class SaveUploadFile {
	public static MultipartRequest getMultipartRequest(HttpServletRequest request, String saveDir) throws Exception{
		int maxPostSize = 100 * 1024 * 1024; // 100MB
		if (!saveDir.trim().endsWith("/")) saveDir+="/";
		File dir = new File(saveDir);
		if (!dir.exists()) dir.mkdirs();
		return new MultipartRequest(request,saveDir,maxPostSize,"utf-8");
	}
	public static List savefile(MultipartRequest multi,String saveDir) throws Exception{
		List list= null;
		HashMap file_info=null;
		if (!saveDir.trim().endsWith("/")) saveDir+="/";

		Enumeration formNames = multi.getFileNames();
		String fileInput = "";   
		String fileName = "";   
		String type = "";   
		File fileObj = null;   
		String originFileName = "";       
		String fileExtend = "";   
		String fileSize = "";
		String file_id = "";
		list = new ArrayList();
		
		while(formNames.hasMoreElements()) {   
	          fileInput = (String)formNames.nextElement();                // 파일인풋 이름   
	
	          fileName = multi.getFilesystemName(fileInput);            // 파일명   
	          if (fileName != null) {   
	               type = multi.getContentType(fileInput);                   //콘텐트타입       
	               fileObj = multi.getFile(fileInput);                             //파일객체   
	               originFileName = multi.getOriginalFileName(fileInput);           //초기 파일명   
	               fileExtend = fileName.substring(fileName.lastIndexOf(".")+1); //파일 확장자   
	               fileSize = String.valueOf(fileObj.length());                    // 파일크기
	               file_id = Integer.toString((int)(Math.random()*100000))+Long.toString(System.currentTimeMillis())+"."+fileExtend;
	               fileObj.renameTo(new File(saveDir+file_id));
	               file_info=new HashMap();
	               file_info.put("fileName",fileName);
	               file_info.put("fileType",type);
	               file_info.put("originFileName",originFileName);
	               file_info.put("fileExtend",fileExtend);
	               file_info.put("fileSize",fileSize);
	               file_info.put("file_id",file_id);
	               file_info.put("fileInput",fileInput);
	               list.add(file_info);
	          }   
		}

		return list;
	}
}
